//
//  COMineViewController.swift
//  CocoProject
//
//  Created by Ruthless on 2023/8/23.
//

import UIKit
import RZColorfulSwift

class COMineViewController: COBaseViewController {
    private var contents: [COMineCellModel] = []
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        configCell()
        
        NotificationCenter.default.addObserver(self, selector: #selector(moneyChange), name: NSNotification.Name("CoinChange"), object: nil)

    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        
        COHomeViewController.getBalance()
        getMine()
        getQAList()
        getSQList()
    }
    override func configUI() {
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: editButton)
        tableView.tableHeaderView = headerView
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    private func configCell() {
        contents = []
        let money = COMineCellModel()
        money.logo = UIImage(named: "金币")
        
        let num = UserDefaults.standard.integer(forKey: "\(COUserManager.userInfo?.id ?? 0)---coin")
        
        money.name = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.text("\(num)")?.font(.medium(22)).textColor(.rgba(152, 48, 255, 1))
        })
        
        money.action = {[weak self] in
            let vc = COWalletController()
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        contents.append(money)
        
        let message = COMineCellModel()
        message.logo = UIImage(named: "message")
        message.name = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.text("Message")?.font(.medium(17)).textColor(.white)
        })
        message.action = {[weak self] in
            let vc = COChatListViewController()
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        contents.append(message)
        
        let question = COMineCellModel()
        question.logo = UIImage(named: "编组 17")
        question.name = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.text("My Question")?.font(.medium(17)).textColor(.white)
        })
        
        question.action = {[weak self] in
            let vc = COQAListViewController(true)
            vc.title = "My Question"
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        
        let qaNum = UserDefaults.standard.integer(forKey: "\(COUserManager.userInfo?.id ?? 0)---QANum")
        question.hintText = "\(qaNum)"
        contents.append(question)
        
        let square = COMineCellModel()
        square.logo = UIImage(named: "picture 2")
        square.name = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.text("My square")?.font(.medium(17)).textColor(.white)
        })
        square.action = {[weak self] in
            let vc = COHomeListViewController(true)
            vc.title = "My Square"
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        let sqNum = UserDefaults.standard.integer(forKey: "\(COUserManager.userInfo?.id ?? 0)---SQNum")
        square.hintText = "\(sqNum)"
        contents.append(square)
        
        let set = COMineCellModel()
        set.logo = UIImage(named: "gear 2")
        set.name = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.text("Setting")?.font(.medium(17)).textColor(.white)
        })
        set.action = {[weak self] in
            let vc = COSettingViewController()
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        contents.append(set)

        tableView.reloadData()
    }
    private lazy var headerView: COMineHeaderView = {
        let view = COMineHeaderView(frame: CGRect(x: 0, y: 0, width: SCREENWIDTH, height: 238+statusBarHeight))
        view.userInfo = COUserManager.userInfo
        return view
    }()
    
    private lazy var tableView: UITableView = {
        let tableV = UITableView()
        tableV.backgroundColor = .rgba(17, 7, 41, 1)
        tableV.contentInsetAdjustmentBehavior = .never
        
        tableV.delegate = self
        tableV.dataSource = self
        tableV.register(cellWithClass: COMineTableViewCell.self)
        tableV.bounces = false
        return tableV
    }()
    
    private lazy var editButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("Edit", for: .normal)
        btn.titleLabel?.font = .medium(18)
        btn.setTitleColor(.white, for: .normal)
        btn.addTarget(self, action: #selector(toEdit), for: .touchUpInside)
        return btn
    }()
}

extension COMineViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return contents.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        contents[indexPath.row].cellHeight
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: COMineTableViewCell.self)
        cell.model = contents[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.contents[indexPath.row].action?()
    }
    
    @objc
    private func moneyChange() {
        configCell()
    }
    
    private func getQAList() {
        CONetwork.sendRequest(provider: mineProvider, target: .qaList(page: 1)) { _ in
        } failedBlock: { _, _ in
        } totalBlock: { number in
            UserDefaults.standard.set(number, forKey: "\(COUserManager.userInfo?.id ?? 0)---QANum")
            UserDefaults.standard.synchronize()
            self.configCell()
        }
    }
    
    private func getSQList() {
        CONetwork.sendRequest(provider: mineProvider, target: .sqList(page: 1)) { _ in
        } failedBlock: { _, _ in
        } totalBlock: { number in
            UserDefaults.standard.set(number, forKey: "\(COUserManager.userInfo?.id ?? 0)---SQNum")
            UserDefaults.standard.synchronize()
            self.configCell()
        }
    }
    
    private func getMine() {
        self.view.makeToastActivity(.center)
        CONetwork.sendRequest(provider: loginProvider, target: .mine) { text in
            self.view.hideToastActivity()
            guard let userInfo = COUserInfo.deserialize(from: text) else {
                return
            }
            userInfo.token = COUserManager.userInfo?.token ?? ""
            COUserManager.userInfo = userInfo
            self.headerView.userInfo = userInfo
        } failedBlock: { _, text in
            self.view.hideToastActivity()
            self.view.makeToast(text, position: .center)
        }
    }
    
    @objc
    private func toEdit() {
        let vc = COProfileViewController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
}
